// src/stores/user.js
import { defineStore } from 'pinia'
import { ElMessage } from 'element-plus'
import { userApi } from '@/api'

export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户信息
    userInfo: null,
    // 用户权限
    permissions: [],
    // 用户菜单
    menus: [],
    // 登录状态
    isLoggedIn: false,
    // token（从localStorage中获取）
    token: localStorage.getItem('token') || null
  }),
  
  getters: {
    // 获取用户名
    username: (state) => state.userInfo?.username || '',
    // 获取用户邮箱
    email: (state) => state.userInfo?.email || '',
    // 获取用户角色
    role: (state) => state.userInfo?.role || '',
    // 检查是否有某个权限
    hasPermission: (state) => (permissionCode) => {
      return state.permissions.includes(permissionCode)
    },
  },
  
  actions: {
    // 设置登录状态
    async setLoginState(data) {
      // 后端返回的是 LoginResultDto: { Token, UserId, RoleId, UserName, |UserInfo| }
            
      // 保存token和用户信息
      this.token = data.token
      this.userInfo = {
        userId: data.userId,
        username: data.userName,
        roleId: data.roleId,
      }
      console.log('userInfo:', this.userInfo)
      this.isLoggedIn = true
      
      // 保存到localStorage
      localStorage.setItem('token', data.token)
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
      
      console.log('Token已保存到localStorage:', localStorage.getItem('token') ? '成功' : '失败')
      
      // 获取用户权限
      try {
        const permissions = await this.fetchUserPermissions(data.userId)
        localStorage.setItem('userPermissions', JSON.stringify(permissions))
        console.log('用户权限已保存到localStorage')
      } catch (error) {
        console.error('获取用户权限失败:', error)
      }
      
      ElMessage.success('登录成功')
    },

    // 用户登出
    logout() {
      // 清除本地数据
      this.clearUserData()
      ElMessage.success('已退出登录')
    },

    // 更新用户信息
    updateUserInfo(data) {
      this.userInfo = { ...this.userInfo, ...data }
      localStorage.setItem('userInfo', JSON.stringify(this.userInfo))
    },

    // 清除用户数据
    clearUserData() {
      this.userInfo = null
      this.permissions = []
      this.menus = []
      this.isLoggedIn = false
      this.token = null
      
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      localStorage.removeItem('userPermissions')
    },

    // 获取用户权限
    async fetchUserPermissions(userId) {
      try {
        console.log('获取用户权限，用户ID:', userId)
        const permissions = await userApi.getUserPermissions(userId)
        console.log('获取到的用户权限:', permissions)
        this.permissions = permissions || []
        return permissions
      } catch (error) {
        console.error('获取用户权限失败:', error)
        this.permissions = []
        return []
      }
    },

    // 初始化用户状态（从localStorage恢复）
    initUserState() {
      const token = localStorage.getItem('token')
      const userInfo = localStorage.getItem('userInfo')
      
      console.log('初始化用户状态:', { 
        token: token ? '存在' : '不存在', 
        userInfo: userInfo ? '存在' : '不存在' 
      })
      
      if (token && userInfo) {
        this.token = token
        this.userInfo = JSON.parse(userInfo)
        this.isLoggedIn = true
        console.log('用户状态已恢复:', this.userInfo)
        
        // 恢复权限信息
        const savedPermissions = localStorage.getItem('userPermissions')
        if (savedPermissions) {
          this.permissions = JSON.parse(savedPermissions)
          console.log('权限信息已恢复:', this.permissions)
        }
      } else {
        console.log('未找到保存的用户状态')
      }
    }
  }
})
